/*
 * Copyright 2003 Jayson Falkner (jayson@jspinsider.com)
 * This code is from "Servlets and JavaServer pages; the J2EE Web Tier",
 * http://www.jspbook.com. You may freely use the code both commercially
 * and non-commercially. If you like the code, please pick up a copy of
 * the book and help support the authors, development of more free code,
 * and the JSP/Servlet/J2EE community.
 */
package com.sanyog.primejsf.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthFilter implements Filter {
  ServletContext sc;
  FilterConfig fc;
  long cacheTimeout = Long.MAX_VALUE;
  private ArrayList<String> urlList; 

  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	System.out.println("Auth Filter"); 
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
   
     String url = request.getServletPath();
 	System.out.println("Auth Filter ::"+url);  
 	System.out.println("urlListr ::"+urlList.get(0));  
 	String[] urlcontains=url.split("\\.");
 	 String temp1 ="";
 	for(int i=0;i<urlcontains.length;i++){ 
 		temp1= urlcontains[1];	
 	}
   
    System.out.println("temp1 ::"+temp1); 
    boolean allowedRequest = false;
     
    if(urlList.get(0).equals(temp1)) {
     	System.out.println("if 1");  
        allowedRequest = true;
    }
         
    if (!allowedRequest) {
    	System.out.println("if 2");  
        HttpSession session = request.getSession(false);
        if (null == session) {
            response.sendRedirect(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/index.xhtml");
        }
    }
     
    chain.doFilter(req, res);
    
  }
  public void init(FilterConfig config) throws ServletException {
      String urls = config.getInitParameter("jsf");
      System.out.println("urls :::"+urls);
      StringTokenizer token = new StringTokenizer(urls, ",");
      urlList = new ArrayList<String>();
      while (token.hasMoreTokens()) {
          urlList.add(token.nextToken());

      }
      this.fc = config;
      String ct = fc.getInitParameter("cacheTimeout");
      if (ct != null) {
        cacheTimeout = 60*1000*Long.parseLong(ct);
      }
      this.sc = config.getServletContext();
  }

  public void destroy() {
    this.sc = null;
    this.fc = null;
  }
}